//
//  GoodsDetailViewController.m
//  StandardizedProduct
//
//  Created by 宁宁 on 16/6/27.
//  Copyright © 2016年 ym. All rights reserved.
//

#import "GoodsDetailViewController.h"

#import "GoodsDetailNavView.h"//导航栏View
#import "GoodsDetailFooterView.h"//页脚View

#import "GoodsDetailView.h"//商品详情View
#import "GoodsDetailTableViewCell.h"//商品详情TableViewCell


#import "BuyWindowView.h"//购买窗View

#import "CommitOrderViewController.h"//提交订单Controller
#import "MerchantViewController.h"//商家Controller

#import "GoodsDetailModel.h"//model
#import "CartModel.h"//购物车model


@interface GoodsDetailViewController ()< UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;

@end

@implementation GoodsDetailViewController
{
    NSUserDefaults *_defaults;
    GoodsDetailView *_infoView;
    GoodsDetailFooterView *_footerView;
    
    /**商品信息Cell高*/
    CGFloat _infoCellHeight;
    /**商品详情cell高*/
    CGFloat _detailCellHeight;
    
    /**商品详情图片item个数*/
    int _numOfDetail;
    
    /**购买窗View*/
    BuyWindowView *_buyWindow;
    /**背景Button*/
    UIButton *_buybgView;
    /**购买窗高*/
    CGFloat _buyViewHeight;
    /**规格数组*/
    NSMutableArray *_standardArray;
    /**判断是加入购物车还是立即购买*/
    NSString *_isBuyRightNow;
    
    
    
    /**购物车数量*/
    NSString *_cartNum;
    
    /**model*/
    GoodsDetailModel *_goodsModel;
}

 static NSString *const GoodsDetailTableViewCellID = @"GoodsDetailTableViewCell";


- (void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden = YES;
    
    
    [self cartPic];
}
- (void)cartPic{
    if ([[_defaults objectForKey:@"CartNum"] intValue] > 0) {
        _cartNum = [_defaults objectForKey:@"CartNum"];
        _footerView.cartNum.text = _cartNum;
        _footerView.cartImgHeight.constant = 24;
        _footerView.cartImage.image = [UIImage imageNamed:@"XQYicon_35"];
    }else{
        _footerView.cartImage.image = [UIImage imageNamed:@"XQYicon0_06"];
        _footerView.cartImgHeight.constant = 20;
    }
}
- (void)viewWillDisappear:(BOOL)animated{
    self.navigationController.navigationBar.hidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    _isCollecting = NO;
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    _defaults = [NSUserDefaults standardUserDefaults];
    
    //设置导航栏和页脚
    [self setNavAndFooter];
    
    //设置cell
    [self setCell];
    
    //网络请求
    [self requestGoodsDetail];
}
#pragma mark === 设置导航栏和页脚 ===
- (void)setNavAndFooter{
    
    //下一级界面返回按钮
    UIBarButtonItem *back = [[UIBarButtonItem alloc] init];
    back.title = @"";
    self.navigationItem.backBarButtonItem = back;
    
    /**Nav按钮*/
    GoodsDetailNavView *navView = [[[NSBundle mainBundle] loadNibNamed:@"GoodsDetailNavView" owner:nil options:nil] lastObject];
    navView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 64);
    navView.navClick = ^(NSString *string){
        //返回
        if ([string isEqualToString:@"back"]) {
            [self.navigationController popViewControllerAnimated:YES];
        //分享
        }else if ([string isEqualToString:@"share"]){
            NSLog(@"分享");
        //商品
        }else if ([string isEqualToString:@"goods"]){
            [_tableView setContentOffset:CGPointZero];
        //详情
        }else if ([string isEqualToString:@"detail"]){
            [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        //评价
        }else{
            NSLog(@"评价");
        }
    };
    [self.view addSubview:navView];
    
    
    /**Footer按钮*/
    _footerView = [[[NSBundle mainBundle] loadNibNamed:@"GoodsDetailFooterView" owner:nil options:nil] lastObject];
    _footerView.frame = CGRectMake(0, SCREEN_HEIGHT - 50, SCREEN_WIDTH, 50);
    //已收藏
    if (_isCollecting) {
        _footerView.collectionImage.image = [UIImage imageNamed:@"XQYicon0_03"];
    }
    //购物车数量
    [self cartPic];
    
    __weak __typeof__ (GoodsDetailFooterView *) weakFooterView = _footerView;
    __weak __typeof__ (self) weakSelf = self;
    _footerView.footerClick = ^(NSString *string){
        //商家
        if ([string isEqualToString:@"merchant"]) {
            MerchantViewController *merchant = [[MerchantViewController alloc] init];
            [weakSelf.navigationController pushViewController:merchant animated:YES];
        //收藏
        }else if ([string isEqualToString:@"collection"]){
            _isCollecting = !_isCollecting;
            if (weakSelf.isCollecting) {
                weakFooterView.collectionImage.image = [UIImage imageNamed:@"XQYicon0_03"];
                [EBUtility prompt:@"已收藏" with:weakSelf];
            }else {
                weakFooterView.collectionImage.image = [UIImage imageNamed:@"XQYicon_41"];
                [EBUtility prompt:@"取消收藏" with:weakSelf];
            }
        //购物车
        }else if ([string isEqualToString:@"cart"]){
            if (weakSelf.tabBarController.selectedIndex == 2) {
                [weakSelf .navigationController popToRootViewControllerAnimated:YES];
            }else weakSelf.tabBarController.selectedIndex = 2;
        //加入购物车
        }else if ([string isEqualToString:@"addToCart"]){
            [weakSelf buyRightNow:0];
        //立即购买
        }else{
            [weakSelf buyRightNow:1];
        }
    };
    [self.view addSubview:_footerView];
}

#pragma mark === 设置cell ===
- (void)setCell{
    _detailCellHeight = SCREEN_WIDTH - 20;
}

#pragma mark === tableview注册 ===
- (void)registerTableView{
    //注册自定义cell
    [self.tableView registerNib:[UINib nibWithNibName:@"GoodsDetailTableViewCell" bundle:nil] forCellReuseIdentifier:GoodsDetailTableViewCellID];
}
#pragma maek === 设置商品详情View ===
- (void)setGoodsDetailView{
    _infoView = [[GoodsDetailView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH * 0.8)];
    [_infoView setScrollView:_goodsModel];
    _infoView.frame = CGRectMake(0, 0, SCREEN_WIDTH, _infoView.height);
    __weak __typeof__ (self) weakSelf = self;
    _infoView.standardClick = ^(){
        [weakSelf buyRightNow:0];
    };
    [_infoView.back addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    self.tableView.tableHeaderView = _infoView;
}

#pragma mark === TableViewDelegate ===
//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _goodsModel.ImageUrlArray.count;
}
//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return _detailCellHeight + 29;
    }
    return _detailCellHeight;
}
//Reusable
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    GoodsDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:GoodsDetailTableViewCellID];
    [cell.detailImage sd_setImageWithURL:[NSURL URLWithString:_goodsModel.ImageUrlArray[indexPath.row]]];
    if (indexPath.row != 0) {
        cell.tuwenXQheight.constant = 0;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark === 立即购买 ===
- (void)buyRightNow:(int) index{
    if (!_buyWindow) {
        _buyWindow = [[BuyWindowView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _buyWindow.standard = _standardArray;
        _buyWindow.model = _goodsModel;
        //刷新View
        [_buyWindow settView];
        _buyViewHeight = _buyWindow.height;
        _buyWindow.view.frame = CGRectMake(0, SCREEN_HEIGHT - 65, SCREEN_WIDTH, _buyViewHeight);
        
        [self.view addSubview:_buyWindow];
        
        __weak __typeof__(self) weakSelf = self;
        __weak __typeof__(BuyWindowView *) weakBuyWindow = _buyWindow;
        _buyWindow.clickBuyRightNow = ^(NSString *click, NSString *standardString){
            if ([click isEqualToString:@"nil"] && [standardString isEqualToString:@"nil"]) {
                [EBUtility prompt:@"库存不足,已为您选择最大库存" with:weakSelf];
            }else if ([weakBuyWindow.num.text isEqualToString:@"0"]) {
                [EBUtility prompt:@"商品无库存" with:weakSelf];
            }else{
                if ([click isEqualToString:@"0"]) {
                    [weakSelf jumpToCommitOrder];
                }else{
                    [EBUtility prompt:[NSString stringWithFormat:@"请选择商品%@", standardString] with:weakSelf];
                }
            }
        };
    }
    
    if (index == 0) {
        _buyWindow.buyLabel.text = @"加入购物车";
        _isBuyRightNow = @"1";
    }else{
        _buyWindow.buyLabel.text = @"立即购买";
        _isBuyRightNow = @"0";
    }
    
    _buyWindow.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    _buyWindow.hiddenWindow.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        _buyWindow.view.frame = CGRectMake(0, SCREEN_HEIGHT - _buyViewHeight, SCREEN_WIDTH, _buyViewHeight);
    }];
}

//立即购买
- (void)jumpToCommitOrder{
    
    if (![_defaults objectForKey:@"UserName"]) {
        [EBUtility prompt:@"请登录" with:self];
        return;
    }
    
    //立即购买
    if ([_isBuyRightNow isEqualToString:@"0"]) {
        
//        [self addToCart];
        
    }else{
        NSLog(@"加入购物车");
        
        [self addToCart];
    }
}

#pragma mark === 网络请求 ===
- (void)requestGoodsDetail{
    NSDictionary *paraments = @{
                                @"productid"   : _modelId,
                                @"productCode" : _modelProductCode
                                };
    
    
    [NetWorkManager requestWithType:HttpRequestTypeGet withMethodName:@"7494/api/Product/GetProductByProductId?" withParaments:paraments withSuccessBlock:^(NSDictionary *object) {
        NSLog(@"%@", object);
        NSLog(@"%@", object[@"SubMessage"]);
        if (isKindOfNSDictionary(object[@"Rows"])) {
            _goodsModel = [GoodsDetailModel parseUserWithDictionary:object[@"Rows"]];
            
            _standardArray = [NSMutableArray array];
            NSDictionary *dic0 = @{@"规格":_goodsModel.NormsDetailNamesArray};
            [_standardArray addObject:dic0];
            
            //tableview注册
            [self registerTableView];
            
            //设置商品详情View
            [self setGoodsDetailView];
        }
        
        
    } withFailureBlock:^(NSError *error) {
        NSLog(@"商品搜索网络请求失败 : %@", error);
    } progress:nil];
}
//加入购物车
- (void)addToCart{
    
    int temp = [_buyWindow.chooseStandardArray[0][0] intValue];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *paraments = @{
                                @"userId"     : [defaults objectForKey:@"Id"],
                                @"userName"   : [defaults objectForKey:@"UserName"],
                                @"skuId"      : _goodsModel.SkuIdArray[temp],
                                @"sKU"        : _goodsModel.SKUArray[temp],
                                @"num"        : _buyWindow.num.text,
                                @"prodtype"   : @"1",
                                @"cangKu"     : @"999999"
                                };
    
    NSLog(@"%@", paraments);
    
    [NetWorkManager requestWithType:HttpRequestTypeGet withMethodName:@"7494/api/Product/AddShopCartItem?" withParaments:paraments withSuccessBlock:^(NSDictionary *object) {
        NSLog(@"%@", object);
        if ([object[@"Code"] isEqualToString:@"0"]) {
            //加入购物车
            if ([_isBuyRightNow isEqualToString:@"1"]) {
                [EBUtility prompt:@"成功加入购物车!" with:self];
                [self requestCartList];
            }
            //立即购买
//            else{
//                [self requestCartList];//获取购物车列表
//            }
        }
    } withFailureBlock:^(NSError *error) {
        NSLog(@"商品搜索网络请求失败 : %@", error);
    } progress:nil];
}
//购物车数量
- (void)requestCartList{
    //列表
    NSDictionary *paraments = @{
                                @"userName"   : [_defaults objectForKey:@"UserName"],
                                @"cKeys"      : @"",
                                @"pageIndex"  : @"1",
                                };
    
    [NetWorkManager requestWithType:HttpRequestTypeGet withMethodName:@"7494/api/Product/GetShopCartListByPage?" withParaments:paraments withSuccessBlock:^(NSDictionary *object) {
        if ([object[@"Code"] isEqualToString:@"0"]) {
            //加入购物车 获取购物车数量
            if ([_isBuyRightNow isEqualToString:@"1"]) {
                [_defaults setObject:[NSString stringWithFormat:@"%@", object[@"TotalCount"]] forKey:@"CartNum"];
                _cartNum = [_defaults objectForKey:@"CartNum"];
                [self cartPic];
            }
            //立即购买 获取购物车第一件商品
//            else{
//                NSDictionary *dic = object[@"Rows"][0];
//                NSLog(@"%@", dic);
//                CartModel *model = [CartModel parseUserWithDictionary:dic];
//                
//                CommitOrderViewController *commit = [[CommitOrderViewController alloc] init];
//                commit.packageArray = @[model];
//                commit.hidesBottomBarWhenPushed = YES;
//                [self.navigationController pushViewController:commit animated:YES];
//            }
        }
    } withFailureBlock:^(NSError *error) {
        NSLog(@"购物车列表请求失败 : %@", error);
    } progress:nil];
}



- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView= [[UITableView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 50) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;//去掉滑动竖条
        _tableView.alwaysBounceVertical = NO;//关闭弹动
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

@end
